package com.tapstitch.scm.pms.web.controller;

import com.bluebuck.quickboot.core.api.dto.ApiResult;
import com.bluebuck.sso.client.admin.auth.model.LoginUser;
import com.bluebuck.sso.client.admin.auth.service.LoginService;
import com.tapstitch.scm.common.core.context.LoginUserContext;
import com.tapstitch.scm.common.page.AjaxResult;
import com.tapstitch.scm.common.utils.DateUtils;
import com.tapstitch.scm.common.utils.excel.ExportFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;

/**
 * web层通用数据处理
 *
 * @author hornbill
 */
public class AdminBaseController {

    @Autowired
    private LoginService loginService;

    protected final Logger logger = LoggerFactory.getLogger(AdminBaseController.class);

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
//    protected void startPage() {
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        Integer pageNum = pageDomain.getPageNum();
//        Integer pageSize = pageDomain.getPageSize();
//        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
//            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
//            PageHelper.startPage(pageNum, pageSize, orderBy);
//        }
//    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
//    protected TableDataInfo getDataTable(List<?> list) {
//        TableDataInfo rspData = new TableDataInfo();
//        rspData.setRows(list);
//        rspData.setTotal(new PageInfo(list).getTotal());
//        return rspData;
//    }


    /**
     * 获取当前登录用户
     */
    protected LoginUser currentUser() {
        return LoginUserContext.getContext().getCurrentUser();
    }

//    @ExceptionHandler({Exception.class})
//    public JsonResult<?> handleException(HttpServletRequest request, HttpServletResponse response, Object handler,
//                                         Throwable ex, Model model) {
//        Object error = processRequestConverterError(ex);
//        if (error != null) {
////            return JsonResult.buildErrorStateResult(MapBuilderUtil.put("errorField", error).build(), "处理异常");
//            return null;
//        }
//        logger.warn("访问页面 " + request.getRequestURI() + " 时发生异常，errorClass:" + ex.getClass().getName() + ", errorMsg:" + ex.getMessage(), ex);
//
//
//        //populateModel(model, request);
//
//        String requestUri = request.getRequestURI();
//        String method = request.getMethod();
//
//        String url = requestUri + " " + method;
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        String userName = (currentUser() == null ? null : currentUser().getUsername());
//        String ip = RequestInfoUtil.getRemoteHost(request);
//
//        /*Map<String, String> build = MapBuilderUtil.put("时间", LocalDate.now().toString())
//                .put("路径", url).put("参数", JSON.toJSONString(parameterMap))
//                .put("用户", (userName == null ? "<无>" : userName)).put("IP", (ip == null ? "<无>" : ip))
//                .put("源类", this.getClass().getName()).build();
//
//        mailSender.sendExceptionEmail(build , appId, ex);*/
//
////        return JsonResult.buildErrorStateResult(MapBuilderUtil.put("errorField", error).build(), "处理异常");
//        return null;
//    }

//    private Object processRequestConverterError(Throwable ex) {
//        if (ex instanceof BindException) {
//            BindException be = (BindException) ex;
//            FieldError fieldError = be.getBindingResult().getFieldError();
//            if (fieldError != null) {
//                return fieldError.getRejectedValue();
//            }
//        }
//        return null;
//    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ApiResult<?> toAjax(int rows) {
        return rows > 0 ? ApiResult.SUCCESS : ApiResult.SYS_ERROR;
    }

    protected AjaxResult toAjaxResult(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return "redirect:" + url;
    }

    protected ResponseEntity<byte[]> exportFile(ExportFile exportFile) throws UnsupportedEncodingException {
        String fileName = exportFile.getFileName();
        byte[] bytes =  exportFile.toByteArray();
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-disposition", "attachment; filename="+fileName);
        httpHeaders.add("Content-Length", bytes.length+"");
        if(exportFile.getContentType() != null){
            httpHeaders.add("Content-Type", exportFile.getContentType());
        }
        return new ResponseEntity<byte[]>(bytes, httpHeaders, org.springframework.http.HttpStatus.CREATED);
    }


}
